package fy.com.controller.main;    
import java.awt.Color;  
import java.awt.image.BufferedImage;  
import java.io.BufferedReader;
import java.io.IOException;  
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.imageio.ImageIO;  
import javax.servlet.http.HttpServletRequest;  
import javax.servlet.http.HttpServletResponse;  

import net.sf.json.JSONObject;

import org.apache.commons.lang3.StringUtils;  
import org.apache.commons.lang3.builder.ReflectionToStringBuilder;  
import org.apache.commons.lang3.builder.ToStringStyle;  
import org.apache.shiro.SecurityUtils;   
import org.apache.shiro.authc.UsernamePasswordToken;  
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;  
import org.apache.shiro.web.util.WebUtils;  
import org.springframework.stereotype.Controller;  
import org.springframework.web.bind.annotation.RequestMapping;  
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.InternalResourceViewResolver;  


import fy.com.controller.base.BaseController;
import fy.com.entity.Page;
import fy.com.service.information.InformationService;
import fy.com.service.status.StatusService;
import fy.com.service.user.RoleService;
import fy.com.service.user.UserService;

import fy.com.util.Const;
import fy.com.util.PageData;
import fy.com.util.VerifyCodeUtil;  

@Controller  
public class LoginController extends BaseController{ 

	@Resource(name="userService")
	private UserService userService;
	@Resource(name="roleService")
	private RoleService roleService;	
	@Resource(name= "statusService")
	private StatusService statusService ;	
	@Resource(name= "informationService")
	private InformationService informationService ;

	/**
	 * 手机端验证
	 */
//	@RequestMapping("loginapp")
//	public void loginApp(HttpServletRequest request,HttpServletResponse response) throws Exception{
//		BufferedReader reader = request.getReader();
//		PageData pd = this.getPageData();
//		String result = "";
//		String line;
//		while((line = reader.readLine())!=null){
//			result += line;
//		}
//		
//		if(TextUtils.isEmpty(result)){
//			System.out.println("请求的登录账号密码为空！！");
//			return;
//		}
//		
//		else{
//			System.out.println(result);
//			JSONObject jsonObject = JSONObject.fromObject(result);
//			String username = jsonObject.getString("username");
//			String userpass = jsonObject.getString("userpass") ;
//			pd.put("uname", username) ;
//			pd.put("upassword", userpass) ;
//			pd = userService.getUserByNameAndPwd(pd);
//			if (pd==null)
//			{
//				System.out.println("账号或者密码不存在！！");
//				response.getWriter().write("false");
//				return ;
//			}
//			else{
//				response.getWriter().write("success");
//			}
//		}
//	}
	
	/**
	 * 访问登录页
	 * @return
	 */
	@RequestMapping(value="/login_toLogin")
	public ModelAndView toLogin()throws Exception{
		ModelAndView mv = this.getModelAndView();
		mv.setViewName("main/login");
		return mv;
	}
	
	/** 
	 * 获取验证码图片和文本(验证码文本会保存在HttpSession中) 
	 */  
	@RequestMapping("/getVerifyCode")  
	public void getVerifyCodeImage(HttpServletRequest request, HttpServletResponse response) throws IOException {  
		//设置页面不缓存  
		response.setHeader("Pragma", "no-cache");  
		response.setHeader("Cache-Control", "no-cache");  
		response.setDateHeader("Expires", 0);  
		String verifyCode = VerifyCodeUtil.generateTextCode(VerifyCodeUtil.TYPE_NUM_ONLY, 4, null); 
		//将验证码放到HttpSession里面  
		request.getSession().setAttribute("verifyCode", verifyCode);  
		System.out.println("本次生成的验证码为[" + verifyCode + "],已存放到HttpSession中");  
		//设置输出的内容的类型为JPEG图像  
		response.setContentType("image/jpeg");  
		BufferedImage bufferedImage = VerifyCodeUtil.generateImageCode(verifyCode, 90, 30, 3, true, Color.WHITE, Color.BLACK, null);  
		//写给浏览器  
		ImageIO.write(bufferedImage, "JPEG", response.getOutputStream());  
	}  


	/** 
	 * 用户登录 
	 */  
	@RequestMapping(value="/login") 
	public ModelAndView login(HttpServletRequest request,Page page) throws Exception{
		ModelAndView mv=this.getModelAndView();
		PageData pd=new PageData();
		pd=this.getPageData(); 
		
		//获取用户名密码
		String resultPageURL = InternalResourceViewResolver.FORWARD_URL_PREFIX + "/";                
		String username = request.getParameter("username");  
		String password = request.getParameter("password");          
		pd.put("uname", username);
		pd.put("upassword", password);
		pd=userService.getUserByNameAndPwd(pd);

		//获取HttpSession中的验证码  
		String verifyCode = (String)request.getSession().getAttribute("verifyCode");  
		//获取用户请求表单中输入的验证码  
		String submitCode = WebUtils.getCleanParam(request, "verifyCode");  
		System.out.println("用户[" + username + "]登录时输入的验证码为[" + submitCode + "],HttpSession中的验证码为[" + verifyCode + "]");  
		if (StringUtils.isEmpty(submitCode) || !StringUtils.equals(verifyCode, submitCode.toLowerCase())){  
			request.setAttribute("message_login", "验证码不正确");  
			mv.setViewName(resultPageURL);
			return mv;
		}
		
		
		if(pd!=null){
			UsernamePasswordToken token = new UsernamePasswordToken(username, password);  
			token.setRememberMe(true);  
			//System.out.println("为了验证登录用户而封装的token为" + ReflectionToStringBuilder.toString(token, ToStringStyle.MULTI_LINE_STYLE));  
			//为了验证登录用户而封装的token为org.apache.shiro.authc.UsernamePasswordToken@76de68c5[
			// username=梅杰
			// password={m,e,i,j,i,e}
			// rememberMe=true
			// host=<null>
			// ]
			//获取当前的Subject  
			Subject currentUser = SecurityUtils.getSubject();  						
			


			//在调用了login方法后,SecurityManager会收到AuthenticationToken,并将其发送给已配置的Realm执行必须的认证检查  
			//每个Realm都能在必要时对提交的AuthenticationTokens作出反应  
			//所以这一步在调用login(token)方法时,它会走到MyRealm.doGetAuthenticationInfo()方法中
			System.out.println("对用户[" + username + "]进行登录验证..验证开始");  
			currentUser.login(token);  
			System.out.println("对用户[" + username + "]进行登录验证..验证通过");  

			
			//授予权限
			Session session = currentUser.getSession();						
			session.setAttribute(Const.SESSION_USERNAME, username);						
			if(null == session.getAttribute(Const.SESSION_QX)){
				session.setAttribute(Const.SESSION_QX, this.getUQX(session));	//按钮权限放到session中
			}
			
			//跳转到地图首页
			PageData pd1=new PageData();
			pd1=this.getPageData();
			page.setPd(pd1);
			List<PageData> dList =   informationService.list(page);
			List<PageData> sList = statusService.list(page) ;
			mv.addObject("dList", dList);
			mv.addObject("sList",sList);
			
			//跳转
			resultPageURL="main/map";

			//验证是否登录成功  
			if(currentUser.isAuthenticated()){  
				System.out.println("用户[" + username + "]登录认证通过");
			}else{  
				token.clear();  
			}  
		}
		else{
			System.out.println("对用户[" + username + "]进行登录验证..验证未通过");  
			request.setAttribute("message_login", "账户或密码有误");
		}		
		mv.setViewName(resultPageURL);
		return mv;

	}  


	/** 
	 * 用户登出 
	 */  
	@RequestMapping("/logout")  
	public ModelAndView logout(HttpServletRequest request){ 
		
		ModelAndView mv = this.getModelAndView();
		Subject currentUser=SecurityUtils.getSubject();
		Session session=currentUser.getSession();
		session.removeAttribute(Const.SESSION_USERNAME);
		session.removeAttribute(Const.SESSION_QX);
		
		
		//shiro销毁登录
		Subject subject = SecurityUtils.getSubject(); 
		subject.logout();
		mv.setViewName("main/login");
		return mv;
		
	}  
	
	
	
	//获取用户权限
	public Map<String, String> getUQX(Session session){
		PageData pd = new PageData();
		Map<String, String> map = new HashMap<String, String>();
		try {
			String uname=session.getAttribute(Const.SESSION_USERNAME).toString();
			pd.put("uname", uname);
			String role_id=userService.findByUname(pd).get("role_id").toString();
			pd.put("role_id", role_id);
			pd=roleService.findObjectById(pd);
			
			map.put("修改设备状态", pd.getString("xsz"));
			map.put("修改测量参数", pd.getString("xcc"));
			map.put("查看测量值和参数", pd.getString("ccc"));
			map.put("管理基本信息", pd.getString("gjx"));
			map.put("查看设备状态", pd.getString("csz"));
			map.put("查看基本信息", pd.getString("cjx"));
			
			System.out.println(map);
		} catch (Exception e) {
			e.printStackTrace();
		}		
		return map;
	}
	
}